<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\TCourseTaskList;
use app\models\TCourseTask;
use app\common\ArrayHelper;
use Faker\Provider\Uuid;
/**
 * APP学员接口类
 * Created by PhpStorm.
 * User: gaoyj
 * Date: 2018/06/25
 */
class TaskController extends Controller
{
	public $enableCsrfValidation = false;
	public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    /**
     * APP提交任务接口
     * @param int  taskId:任务ID userId:用户ID projectId:联盟ID
     * @param int  report_content:任务内容 token:token
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2021-06-07
     */
    public function actionSubmitCourseTask()
    {
		$error          = array();
		$taskId         = isset($_REQUEST['taskId'])?$_REQUEST['taskId']:$error[]=array('子任务ID不能为空');
		$file_id        = !empty($_REQUEST['file_id'])?$_REQUEST['file_id']:'';
		$report_id      = !empty($_REQUEST['report_id'])?$_REQUEST['report_id']:'';
		$userId         = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
		$start_time     = !empty($_REQUEST['start_time'])?$_REQUEST['start_time']:$error[]=array('开始时间不能为空');
		$report_content = isset($_REQUEST['report_content'])?$_REQUEST['report_content']:$error[]=array('任务内容不能为空');
		$projectId      = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if (!empty($error)) {
        	$this->ReturnData('601','缺少请求参数',['status' => '','old_id'=>'']);
        } else {
            $task = TCourseTaskList::findOne($taskId);
            if(!$task){
            	$this->ReturnData('602','缺少请参数错误求参数',['status' => '','old_id'=>'']);
            }
            $report_back_status = TCourseTaskReport::find()->select('report_status,submit_time')->where('task_id=:task_id and create_by=:create_by and del_flag=0',[':task_id' => $task->task_id,':create_by' => $userId])->asArray()->one();
            $status = TCourseTask::find()->where('id=:id and del_flag=0',[':id' => $task->task_id])->one();
            if ($report_back_status['report_status']=='reportStatus.back') {
                if (!empty($report_back_status['submit_time']) && $report_back_status['submit_time']!='0000-00-00 00:00:00') {
                    if (strtotime($report_back_status['submit_time']) < time()) {
                    	$this->ReturnData('400','本次任务时间已结束！',['status' => '','old_id'=>'']);
                    }
                }
            } else {
                if ($status) {
                    if (!empty($status->deadline) && $status->deadline!='0000-00-00 00:00:00') {
                        if (strtotime($status->deadline)<time()) {
                        	$this->ReturnData('400','本次任务时间已结束！',['status' => '','old_id'=>'']);
                        }
                    }
                    if ($status->task_status=='activityStatus.over') {
                    	$this->ReturnData('400','该任务已结束',['status' => '','old_id'=>'']);
                    }
                } else {
                	$this->ReturnData('400','该任务已结束',['status' => '','old_id'=>'']);
                }
            }
            $courseStatus = TCourseInfo::findOne($status->t_course_id);
            if ($courseStatus) {
                if ($courseStatus->course_status!='courseCheckStatus.release') {
                	$this->ReturnData('400','该课程已结束',['status' => '','old_id'=>'']);
                }
            } else {
            	$this->ReturnData('602','参数错误',['status' => '','old_id'=>'']);
            }
            if (!empty($report_id)) {
                $transaction = \Yii::$app->db->beginTransaction();
                $model = TCourseTaskReport::find()->select('old_id')->where('id=:report_id and del_flag=0',[':report_id' => $report_id])->one();
                $res = \Yii::$app->db ->createCommand()->update('t_course_task_report',[
                            'report_content' => $report_content,
                            'report_status' => 'reportStatus.submit',
                            'update_by' => $userId,
                            'update_time' => date("Y-m-d H:i:s"),
                            ],"id='".$report_id."' and del_flag=0")
                        ->execute();
                if ($res) {
                    if (!empty($file_id)) {
                        $ids = explode(',', $file_id);
                        $fileId = implode("','",$ids);
                        $sql = "update t_course_task_file set del_flag = 1,update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where report_id='".$report_id."'";
                        $file_res = \Yii::$app->db->createCommand($sql)->execute();
                        $sql1 = "update t_course_task_file set del_flag = 0,report_id='".$report_id."',update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where id IN('".$fileId."')";
                        $res1 = \Yii::$app->db->createCommand($sql1)->execute();
                        if ($res1) {
                            $transaction->commit();
                            $this->ReturnData('200','操作成功',['status'=>'','old_id'=>!empty($model->old_id)?$model->old_id:'']);
                        } else {
                            $transaction->rollback();
                            $this->ReturnData('400','操作失败',['status'=>'','old_id'=>'']);
                        }
                    } else {
                        $sql = "update t_course_task_file set del_flag = 1,update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where report_id='".$report_id."'";
                        $file_res = \Yii::$app->db->createCommand($sql)->execute();
                        $transaction->commit();
                        $this->ReturnData('200','操作成功',['status'=>'','old_id'=>'']);
                    }
                } else {
                	$this->ReturnData('400','提交失败',['status'=>'','old_id'=>'']);
                }
            } else {
                $transaction = \Yii::$app->db->beginTransaction();
                $model = TCourseTaskReport::find()->where('task_id=:task_id and create_by=:create_by and del_flag=0',[':task_id' => $task->task_id,':create_by' => $userId])->one();
                if ($model) {
                    $model->group_id = $taskId;
                    $model->report_title = $task->task_title;
                    $model->report_content = $report_content;
                    $model->report_status = 'reportStatus.submit';
                    $model->update_by = $userId;
                    $model->update_time = date("Y-m-d H:i:s");
                    if ($model->save()) {
                        $id = $model->id;
                        $file_up_flag = false;
                        if (!empty($file_id)) {
                            $ids = explode(',', $file_id);
                            $fileId = implode("','",$ids);
                            $sql1 = "update t_course_task_file set del_flag = 1,update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where report_id='".$id."'";
                            $res = \Yii::$app->db->createCommand($sql1)->execute();
                            $sql = "update t_course_task_file set report_id = '".$id."',create_by = '".$userId."'  where id in ('".$fileId."')";
                            $file_res = Yii::$app->db->createCommand($sql)->execute();
                            if($file_res){
                                $file_up_flag = true;
                            }
                        } else {
                            $report = \app\models\TCourseTaskFile::find()->where('report_id=:id',[':id'=>$id])->all();
                            if (!empty($report)) {
                                $res = \app\models\TCourseTaskFile::updateAll(['del_flag'=>1,'update_by'=>$userId,'update_time'=>date("Y-m-d H:i:s")],['report_id'=>$id]);
                            } else {
                                $res = true;
                            }
                            if ($res) {
                                $file_up_flag = true;
                            }
                        }
                        if ($file_up_flag) {
                            $time = date("Y-m-d H:i:s");
                            $send_data = [
                                'tasksEvaluationid' => !empty($model->old_id)?$model->old_id:'',
                                'userid' => PdUtils::getOldId('t_base_user',$userId),
                                'launchCourseid' => $courseStatus->old_id,
                                'learningTasksid' => PdUtils::getOldId('t_course_task',$task->task_id),
                                'status' => '已提交',
                                'startdotime' => $start_time,
                                'gradetime' => $time,
                                'submittime' => $time,
                                'modifiedtime' => $time,
                                'bcourseid' => PdUtils::getOldIdByTid($courseStatus->id),
                                'projectid' => $projectId,
                            ];
                            @PdUtils::SaveMongoData($send_data, 'correcting');
                            $transaction->commit();
                            $this->ReturnData('200','操作成功',['status'=>'','old_id'=>!empty($model->old_id)?$model->old_id:'']);
                        } else {
                            $transaction->rollback();
                            $this->ReturnData('400','操作失败',['status'=>'','old_id'=>'']);
                        }
                        Yii::$app->end(json_encode($result));
                    } else {
                    	$this->ReturnData('400','提交失败',['status'=>'','old_id'=>'']);
                    }
                }
            }
        }
    }
    /**
     * APP任务详情接口
     * @param int  taskId:任务ID
     * @return mixed 错误返回NULL，正确返回json
     */
    public function actionGetCourseTaskInfo()
    {
		$error      = array();
		$taskId     = isset($_REQUEST['taskId'])?$_REQUEST['taskId']:$error[]=array('任务ID不能为空');

        if (!empty($error)) {
        	$this->ReturnData('601','缺少请求参数');
        } else {
            $task = TCourseTask::find()->select('id,task_title,task_content,task_score,group_way,end_time,task_status,task_experience')->where('id=:id', [':id' => $taskId])->asArray()->one();
            if ($task) {
                $task_list = TCourseTaskList::find()->select('id,task_id,task_title,task_content')->where('task_id=:id', [':id' => $taskId])->asArray()->all();
                $task['task_list'] = ArrayHelper::array_is_null($task_list);
                $this->ReturnData('200','查找成功',$task);
            } else {
                $this->ReturnData('404','数据为空');
            }
        }
    }
    /*
     * 任务附件上传
     */
    public function actionTaskFilesInput()
    {
		$error    = array();
		$userId   = empty($_REQUEST['userId']) ? $error[]=array('用户ID不能为空') : $_REQUEST['userId'];
		$courseId = empty($_REQUEST['courseId']) ? $error[]=array('课程ID不能为空') : $_REQUEST['courseId'];
        if (!empty($_FILES) && !empty($courseId) && !empty($userId)) {
            $projectId = \app\models\TCourseInfo::findOne($courseId)['project_id'];
            if (!empty($projectId)) {
                $path = 'files'.DIRECTORY_SEPARATOR.$projectId.DIRECTORY_SEPARATOR.'teach'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'task'.DIRECTORY_SEPARATOR;
            } else {
                $path = 'files'.DIRECTORY_SEPARATOR.'teach'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'task'.DIRECTORY_SEPARATOR;
            }
            if (!is_dir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path)) {
                mkdir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path, 0777, true);
            }
            $fileformat =  substr($_FILES['files']["name"], strrpos($_FILES['files']["name"], '.')+1);
            $uri = $path.md5($_FILES['files']["name"]. time()).'.'.$fileformat;
            if (move_uploaded_file($_FILES['files']["tmp_name"],\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri)) {
                $model = new \app\models\TCourseTaskFile();
                $model->id=Uuid::uuid();
                $model->name=$_FILES['files']["name"];
                $model->file_uri=$uri;
                $model->size= $_FILES['files']["size"];
                $model->create_by = $userId;
                $model->create_time = date('Y-m-d H:i:s', time());
                $model->type = $fileformat;
                $model->mime = $_FILES['files']["type"];
                $model->del_flag = 0;
                if ($model->validate() && $model->save()) {
                	$arr=array(
                        'fid'=>$model->attributes['id'],
                        'filename' => $_FILES['files']["name"],
                        'type' => $_FILES['files']["type"],
                        'size' => $_FILES['files']["size"],
                        'url' => Yii::$app->params['fileUrl'].$uri
                    );
                    $this->ReturnData('200','保存成功',$arr);
                } else {
                	$this->ReturnData('400','保存失败');
                }
            } else {
            	$this->ReturnData('400','保存失败');
            }
        }else{
        	$this->ReturnData('601','缺少参数');
        }
    }
    public function ReturnData($code,$msg,$data=[])
    {
        $result = [
            'msg' => $msg,
            'data' => $data,
            'code' => $code
        ];
        Yii::$app->end(json_encode($result));
    }
}